package com.aliyun.messagemgt.repository.task;

import com.aliyun.messagemgt.common.constants.SmsQuotaConstant;
import com.aliyun.messagemgt.dto.MsgSource;
import com.aliyun.messagemgt.dto.SmsQuota;
import com.aliyun.messagemgt.dto.SmsQuotaDefaultConfig;
import com.aliyun.messagemgt.domain.repository.MsgSourceRepository;
import com.aliyun.messagemgt.domain.repository.SmsQuotaConfigRepository;
import com.aliyun.messagemgt.domain.repository.SmsQuotaRepository;
import com.aliyun.messagemgt.domain.repository.task.BaseTask;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 给历史（或者未配置短信配额的）短信消息源初始化短信配额 定时任务
 *
 * @author byp
 * @date 2020/7/13
 */
@DisallowConcurrentExecution
@Component
public class InitHistorySmsQuotaTask implements BaseTask {

    @Resource
    private MsgSourceRepository msgSourceRepository;
    @Resource
    private SmsQuotaRepository smsQuotaRepository;
    @Resource
    private SmsQuotaConfigRepository smsQuotaConfigRepository;

    private final Logger logger = LoggerFactory.getLogger(InitHistorySmsQuotaTask.class);

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        logger.info("初始化短信消息源默认配额 begin");
        List<MsgSource> unboundList = msgSourceRepository.queryUnboundSmsQuotaMsgSource();
        if (unboundList.size() <= 0) {
            logger.info("没有未设置短信配额的短信消息源");
            return;
        }
        SmsQuotaDefaultConfig config = smsQuotaConfigRepository.queryConfig(null);
        if (config == null) {
            logger.info("没有找到默认短信配额");
            return;
        }

        SmsQuota smsQuota = new SmsQuota().setQuota(config.getQuota())
                .setQuotaType(config.getQuotaType());
        for (MsgSource msgSource : unboundList) {
            smsQuota.setMsgSourceId(msgSource.getSourceCode())
                    .setEffectiveStatus(SmsQuotaConstant.EFFECTIVE_STATUS_SHENGXIAO)
                    //立即生效
                    .setEffectiveType(SmsQuotaConstant.EFFECTIVE_TYPE_NOW)
                    .setEffectiveBeginTime(new Date())
                    .setUpdateTime(new Date())
                    .setUpdateUserName("system");
            int result = smsQuotaRepository.insert(smsQuota);
            if (result < 1) {
                logger.info("初始化消息源：{} 默认短信配额失败", msgSource.getSourceCode());
                continue;
            }
            logger.info("初始化消息源：{} 默认短信配额成功", msgSource.getSourceCode());
        }
        logger.info("初始化短信消息源默认配额 end");
    }


    @Override
    public String getName() {
        return "InitHistorySmsQuotaTask";
    }

    @Override
    public String getGroup() {
        return "InitHistorySmsQuotaTask";
    }
}
